// pages/certification/certification.js
const app = getApp()
var util =  require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnTxt:{
      btnTxt:'提交认证'
    },
    btnTxt2:{
      btnTxt2:'重新认证'
    },
    flag : false,
    codeDis : false,
    phoneCode : "获取验证码",
    state:false,
    evalList: [{ tempFilePaths: [], imgList: [] }],
    typeList:[{
      name: '健康管理师认证',
      check: false,
      src: '/resources/my-image/type1.png',
      type: '1'
    },{
      name: '血糖管理师认证',
      check: false,
      src: '/resources/my-image/type2.png',
      type: '2'
    },{
      name: '血压管理师认证',
      check: false,
      src: '/resources/my-image/type3.png',
      type: '3'
    }],
    isShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.isCertification){
      that.setData({
        isCertification: options.isCertification,
      })
    }
    if(options.stateList)
    {
      if(that.data.isCertification == 2)
      {
        that.setData({
          stateList : JSON.parse(options.stateList)
        })
        that.setType(that.data.stateList)
        that.againNewType(that.data.stateList)
      }
    }
  },

  //设置类别
  setType:function(stateList){
    var that = this
    for(var i in stateList){
      var state = "stateList[" + i + "].state"
      var name = "stateList[" + i + "].name"
      var status =  that.certificationState(stateList[i].status)
      var type = that.certificationType(stateList[i].type)
      that.setData({
        [state] : status,
        [name]: type
      })
    }
    that.setData({
      stateList : stateList
    })
    for(var j in stateList){
      if(stateList[j].status == 3){
        var btnTxt2 = 'btnTxt2.btnTxt2';
        that.setData({
          [btnTxt2] : '重新认证',
          isShow: true
        })
      }
    }
  },

  //认证类别
  certificationType:function(type){
    var name = ''
    if(type == 1){
      name = '健康管理师认证'
    }
    else if(type == 2){
      name = '血糖管理师认证'
    }
    else if(type == 3){
      name = '血压管理师认证'
    }
    return name
  },

  //认证状态
  certificationState:function(status){
    var that = this;
    var state = ''
    var btnTxt2 = 'btnTxt2.btnTxt2';
    // console.log(state)
    if(status == 1)
    {
      state = '审核中'
    }
    else if(status == 2)
    {
      state = '审核成功'
      that.setData({
        [btnTxt2] : '继续认证',
        isShow: true
      })
    }
    else if(status == 3)
    {
      state = '审核失败，请重新审核'
      that.setData({
        [btnTxt2] : '重新认证',
        isShow: true
      })
    }
    return state
  },

  againNewType:function(stateList){
    var that = this
    var stateList = that.data.stateList;
    var typeList = that.data.typeList;
    var list = []
    if(stateList){
      for(var j in stateList){
        if(stateList[j].type == 1 && stateList[j].status == 2)
        {
          typeList[0].check = true
          list.push(typeList[0])
        }
        if(stateList[j].type == 2 && stateList[j].status == 2)
        {
          typeList[1].check = true
          list.push(typeList[1])
        }
        if(stateList[j].type == 3 && stateList[j].status == 2)
        {
          typeList[2].check = true
          list.push(typeList[2])
        }
      }
      that.setData({
        typeList: typeList,
        arr: list
      })
    }
  },

  phoneInput:function(e){
    let value = e.detail.value
    this.setData({
        phone : value
    })
  },

  //提交表单
  formSubmit:function(e){
    var that = this
    // console.log(e)
    var name = e.detail.value.name;
    // var phone = e.details.value.phone;
    var sms =  e.detail.value.sms;
    var idcard = e.detail.value.idcard;
    var number = e.detail.value.number;
    if (name == "" || idcard == ""){
      util.showModal('提示','请填写完整信息')
      return
    }
    if(name.length > 0)
    {
      var type= 'name'
      var validation = util.validation(name,type)
      if(validation){
        that.setData({
          name: name
        })
      }
      else{
        util.showModal('提示','姓名输入不正确')
        return
      }
    }else{
      util.showModal('提示','姓名输入不正确')
      return
    }
    if (idcard.length <= 18) {
      var type= 'idcard'
      var validation = util.validation(idcard,type)
      if(validation){
        that.setData({
          idcard: idcard
        })
      }
      else{
        util.showModal('提示','身份证号输入不正确')
        return
      }
    }
    if(number.length > 0 && number != '')
    {
      var type= 'alphanumeric'
      var validation = util.validation(number,type)
      if(validation){
        that.setData({
          number: number
        })
      }
      else{
        util.showModal('提示','授权编号输入不正确')
        return
      }
    }else{
      that.setData({
        number: number
      })
    }
    if(sms != ''){
      if(that.data.code!= '')
      {
        if(sms != that.data.code)
        {
          util.showModal('提示','短信验证码输入不正确，请重新输入')
          return
        }
      }
      else{
        util.showModal('提示','请获取短信验证码')
        return
      }
    }
    else{
      util.showModal('提示','短信验证码不能为空')      
      return
    }
  },

  //获取验证码
  smsBtn: function (options) {
    var that = this
    var phone = that.data.phone
    if(that.validationPhone(phone))
    {
      that.setData({
        codeDis : true
      })
      wx.request({
        url: app.globalData.apiUrl +'/sms',
        data: {
          phone: phone
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.Code != "OK"){
            that.setData({
                codeDis : false
            })
            wx.showToast({
                title: '获取验证码失败，请重新获取',
                icon : "loading"
            })
            setTimeout(function(){
                wx.hideToast()
            },2000)
          }
          else{
            that.setData({
              phoneCode : 60,
              code: res.data.yzm
            })
            let time = setInterval(()=>{
              var phoneCode = that.data.phoneCode
              phoneCode --
              that.setData({
                  phoneCode : phoneCode
              })
              if(phoneCode == 0){
                clearInterval(time)
                that.setData({
                  phoneCode : "获取验证码",
                  flag : true,
                  codeDis : false
                })
              }
            },1000)
          }
        },
        fail: function (res) {
          console.log("失败");
        }
      })
    }
  },

  //验证手机号
  validationPhone:function(phone){
    if(!phone)
    {
      util.showModal('提示','手机号不能为空')      
      return false
    }
    if (phone.length === 11) {
      var type = 'phone'
      var validation = util.validation(phone,type)
      if(validation){
        return true
      }
      else{
        util.showModal('提示','手机号输入不正确')
        return false
      }
    }else{
      util.showModal('提示','手机号输入不正确')
      return false
    }
  },

  //选择状态
  typeBtn:function(e){
    var that = this
    var type = e.currentTarget.dataset.type;
    var typeList = that.data.typeList;
    var arr = []
    for(var i in typeList)
    {
      if(type == typeList[i].type)
      {
        typeList[i].check = !typeList[i].check
      }
      if(typeList[i].check){
        arr.push(typeList[i])
      }
    }
    that.setData({
      typeList:typeList,
      arr: arr
    })
  },

  //添加图片
  joinPicture: function (e) {
    var index = e.currentTarget.dataset.index;
    var evalList = this.data.evalList;
    var that = this;
    var imgNumber = evalList[index].tempFilePaths;
    if (imgNumber.length >= 3) {
      util.showModal('提示','最多上传三张图片')
      return;
    }
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", imgNumber);
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", imgNumber);
          }
        }
      }
    })
  },
  //选择图片
  chooseWxImage: function (type, list) {
    var img = list;
    var len = img.length;
    var that = this;
    var evalList = this.data.evalList;
    wx.chooseImage({
      count: 3,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function (res) {
        console.log(res)
        var addImg = res.tempFilePaths;
        var addLen = addImg.length;
        if ((len + addLen) > 3) {
          for (var i = 0; i < (addLen - len); i++) {
            var str = {};
            str.pic = addImg[i];
            img.push(str);
          }
        } else {
          for (var j = 0; j < addLen; j++) {
            var str = {};
            str.pic = addImg[j];
            img.push(str);
          }
        }
        that.setData({
          evalList: evalList
        })
        that.upload(img);
      },
    })
  },

  //删除图片
  clearImg: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var evalList = this.data.evalList;
    var img = evalList[0].tempFilePaths;
    img.splice(index, 1);
    that.setData({
      evalList: evalList
    })
    that.upload(img);
  },

  //多张图片上传
  upload: function (path) {
    var that = this;
    var curImgList = [];
    for (var i = 0; i < path.length; i++) {
      wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
        wx.uploadFile({
          url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
          filePath: path[i].pic,
          name: 'img',
          header: { "Content-Type": "multipart/form-data" },
          formData: {
            douploadpic: '1'
          },
          success: function (res) {
            // console.log(res)
            if (res.statusCode != 200) {
              util.showModal('提示','上传失败')
              return;
            }else{
              curImgList.push(app.globalData.apiUrl + '/upload/'+ res.data);
              var evalList = that.data.evalList;
              evalList[0].imgList = curImgList;
              that.setData({
                evalList: evalList
              })
            }
          },
          fail: function (e) {
            util.showModal('提示','上传失败')
            return
          },
          complete: function () {
            wx.hideToast();  //隐藏Toast
          }
        })
    }
  },

  IsAddImg:function(){
    var that = this
    var evalList = that.data.evalList;
    var imgList = evalList[0].imgList;
    var imgPort = "";//图片地址，多张以逗号分割
    if (imgList.length != 0) {
      for (var j = 0; j < imgList.length; j++) {
        if(imgList.length==1)
        {
          imgPort = imgList[j];
        }else{
          imgPort = imgList[j] + "," + imgPort;
        }
      }
    } else {
      imgPort = "";
    }
    return imgPort
  },

  //是否有状态
  isType:function(){
    var that = this
    var typeList = that.data.arr;
    if(typeList){
      var types = ""
      for(var i in typeList){
        if(typeList.length==1)
        {
          types = typeList[i].type;
        }else{
          types = typeList[i].type + "," + types;
        }
      }
      return types
    }else{
      return false
    }
  },

  //认证点击事件
  lickBtn: function () {
    var that = this
    if(that.data.name && that.data.phone && that.data.idcard)
    {
      var types = that.isType();
      if(types == false){
        util.showModal('提示','请选择管理师类别')
        return
      }
      var imgPort = that.IsAddImg();
      // console.log(types)
      wx.request({
        url: app.globalData.apiUrl +'/posteam',
        data: {
          userId: app.globalData.userId,
          uname: that.data.name,
          mobile: that.data.phone,
          carId: that.data.idcard,
          img: imgPort,
          type: types,
        },
        method: 'post',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.setData({
              isCertification: 2,
            })
            //返回
            wx.navigateBack({
              delta:1
            })
          }else{
            util.showModal('提示','认证失败，请重新认证')
            return
          }
        },
        fail: function (res) {
          console.log("失败");
        }
      })
    }
    else{
      util.showModal('提示','请填写完整信息')
      return
    }
  }, 

  //重新认证
  lickBtn2:function(){
    var that = this;
    that.setData({
      isCertification: 1,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN健康管理',
      path: 'pages/index/index',
      success: function(res) {
        // res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})